<template>
  <div class="article-list" ref="ArticleList" @scroll="rememberScroll">
    <van-pull-refresh
      v-model="refreshing"
      @refresh="onRefresh"
      success-text="刷新成功"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        @load="onLoad()"
        finished-text="没有更多了"
      >
        <article-item
          v-for="article in articleList"
          :key="article.id"
          :article="article"
        ></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import articleItem from './articleItem.vue'
import { getChannelArticleList } from '@/api/channel'
export default {
  props: {
    currentId: {
      type: Number,
      default: 0
    }
  },
  components: {
    articleItem
  },
  data () {
    return {
      timestamp: +new Date(),
      articleList: [],
      loading: false,
      finished: false,
      refreshing: false,
      scrollTop: 0
    }
  },
  created () {
    this.getArticleList()
  },
  // 激活组件
  activated () {
    this.$refs.ArticleList.scrollTop = this.scrollTop
  },
  methods: {
    rememberScroll () {
      this.scrollTop = this.$refs.ArticleList.scrollTop
    },
    async getArticleList () {
      const [err, data] = await getChannelArticleList({
        channel_id: this.currentId,
        timestamp: this.timestamp
      })
      if (err) return this.$toast.fail(err)
      console.log('article数据获取成功', data)
      this.articleList = data.data.data.results
    },
    // 上拉加载
    async onLoad () {
      const [err, data] = await getChannelArticleList({
        channel_id: this.currentId,
        timestamp: this.timestamp
      })
      if (err) return this.$toast.fail(err)
      console.log('上拉数据请求成功', data)
      // if (data && data.data.data && data.data.data.results && data.data.data.results.length === 0) {
      //   this.loading = false
      //   this.finished = true
      //   return
      // }

      if (data.data.data.pre_timestamp) {
        this.timestamp = data.data.data.pre_timestamp
      } else {
        this.finished = true
      }

      this.articleList.push(...data.data.data.results)
      this.loading = false
    },
    // 下拉刷新
    async onRefresh () {
      this.timestamp = Date.now()
      const [err, data] = await getChannelArticleList({
        channel_id: this.currentId,
        timestamp: this.timestamp
      })
      if (err) return this.$toast.fail(err)
      console.log('下拉刷新请求成功', data)
      this.finished = false
      this.timestamp = data.data.pre_timestamp
      this.refreshing = false
    }
  }
}
</script>
<style scoped lang="less">
.article-list {
  height: 100%;
  overflow-y: auto;
  padding: 0 16px;
}
</style>
